﻿/********************************************************
 * Module Name    : Zoom Across from Toolbar
 * Purpose        : Gets the list of tables to be shown in dropdown under zoom across button
 * Class Used     : ZoomTarget.cs
 * Chronological Development
 * Lakhwinder    19-Aug-2011
 ******************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.Logging;
using VAdvantage.Apps;
using VAdvantage.Utility;
using System.Windows.Input;
using System.Windows.Controls;

namespace VAdvantage.Classes
{

    class AZoomAcross
    {
        //	Query
        private Query query;
        //	The Popup
        // private System.Windows.Forms.ToolStripDropDown popup = new System.Windows.Forms.ToolStripDropDown();
        //	The Option List
        private List<KeyNamePair> list = new List<KeyNamePair>();
        //	Logger
        private static VLogger log = VLogger.GetVLogger(typeof(AZoomAcross).FullName);
        ATreeViewItem m_all = null;
        ATreeViewItem menuItem = null;
        private IBusy _busy = null;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="btn">button object</param>
        /// <param name="tableName">table name</param>
        /// <param name="qry">query</param>
        /// <param name="curWindowID">current window id</param>
        public AZoomAcross(Apps.AppsAction btn, String tableName, Query qry, int curWindowID,IBusy busy)
        {

            _busy = busy;
            log.Config("TableName=" + tableName + " - " + query);
            query = qry;

            //	See What is there
            GetZoomTargets(btn, tableName, curWindowID);
            // set recordcount of query, so that lookup window does not opens while opening the window
            query.SetRecordCount(1);
        }

        /// <summary>
        /// Get the Zomm Targets for the table and Fill the list and the popup menu.
        /// </summary>
        /// <param name="zoomButton">button object</param>
        /// <param name="tableName">table name</param>
        /// <param name="curWindowID">current window id</param>
        private void GetZoomTargets(Apps.AppsAction zoomButton, String tableName, int curWindowID)
        {

            
            //zoomButton.DropDown = null;
            //System.Windows.Forms.ToolStripMenuItem menuItem = null;
             menuItem = zoomButton.GetTreeViewItem();

             //Check User Re-Click onParent Item

             if (menuItem.Items.Count > 0) //Has Already Processed
             {
                 SetBusy(false);
                 return;
             }
            // menuItem.Items.Clear();
            // set sql query
            String sql = "SELECT DISTINCT t.AD_Table_ID, t.TableName "
                + "FROM AD_Table t "
                + "WHERE EXISTS (SELECT 1 FROM AD_Tab tt "
                    + "WHERE tt.AD_Table_ID = t.AD_Table_ID AND tt.SeqNo=10) "
                + " AND t.AD_Table_ID IN "
                    + "(SELECT AD_Table_ID FROM AD_Column "
                    + "WHERE ColumnName='" + tableName + "_ID') "
                + "AND TableName NOT LIKE 'I%'"
                + "AND TableName NOT LIKE '" + tableName + "' "
                + "ORDER BY 1";

            IDataReader dr = null;
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    dr = DataBase.DB.ExecuteReader(sql);
                   
                        while (dr.Read())
                        {
                            List<KeyNamePair> zoomList = new List<KeyNamePair>();
                            // get table name
                            string targetTableName = dr["TableName"].ToString();
                            // get target table names for above table
                            zoomList = ZoomTarget.GetZoomTargets(targetTableName, curWindowID, query.GetWhereClause());

                            if (zoomList != null)
                            {
                                for (int i = 0; i < zoomList.Count; i++)
                                {
                                    KeyNamePair pp = zoomList[i];
                                    if (!list.Contains(pp))
                                    {
                                        list.Add(pp);
                                        String windowName = pp.ToString();
                                        
                                    }
                                }
                            }
                        }
                        // close data reader
                        dr.Close();

                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                        {


                            //	No Zoom
                            if (list.Count == 0)
                            {
                                
                                ShowMessage.Info("NoZoomTarget", true, "", "");
                            }
                            else
                            {
                               
                              
                                for(int i=0;i<list.Count;i++)
                                {
                                    m_all = new ATreeViewItem()
                                     {
                                         Header = Msg.GetMsg(Envs.GetCtx(), list[i].ToString())
                                     };
                                    m_all.Click += Item_Click;
                                    menuItem.Items.Add(m_all);
                                }
                               
                               menuItem.IsExpanded = true;                              
                             
                            }
                           SetBusy(false);
                        });
                    });

               //SetBusy(true);
                
               

            }
            catch (Exception ex)
            {
                if (dr != null)
                {
                    dr.Close();
                }
                // fill error log
                log.Log(Level.SEVERE, sql, ex);
            }

        }

        private void SetBusy(bool busy)
        {
            if(_busy != null)
            {
                _busy.SetBusy(busy);
            }
        }



        private void Dispose(bool dispose)
        {
            if (menuItem != null)
            {
                //menuItem.Items
                if (dispose)
                {
                    menuItem.Items.Clear();

                }
                foreach (TreeViewItem itm in menuItem.Items)
                {
                    ((ATreeViewItem)itm).Click -= Item_Click;
                }

               // menuItem.Items.Clear();  
            }
            list.Clear();
            m_all = null;
            _busy = null;

        }


        void Item_Click(object sender, EventArgs e)
        {
            //menuItem.IsExpanded = false;
            ATreeViewItem tp = (ATreeViewItem)sender;
            string cmd = tp.Header.ToString();
            for (int i = 0; i < list.Count; i++)
            {
                KeyNamePair pp = (KeyNamePair)list[i];
                if (cmd.Equals(pp.GetName()))
                {
                    //menuItem.Items.Clear();
                    LaunchZoom(pp);
                    break;
                }
            }
            Dispose(false);
            
        }

        //private void menuItem_Click(object sender, EventArgs e)
        //{
        //    // get clicked item's text
        //    //System.Windows.Forms.ToolStripMenuItem item = (System.Windows.Forms.ToolStripMenuItem)sender;
        //    var item = sender;
        //    string cmd = sender.ToString();

        //    for (int i = 0; i < list.Count; i++)
        //    {
                
        //        cmd = m_all.Header.ToString();
        //        KeyNamePair pp = (KeyNamePair)list[i];
        //        if (cmd.Equals(pp.GetName()))
        //        {
        //            LaunchZoom(pp);
        //            return;
        //        }
        //    }
        //}



        /// <summary>
        /// Opens the window
        /// </summary>
        /// <param name="pp">KeyPair</param>
        private void LaunchZoom(KeyNamePair pp)
        {
           
            int AD_Window_ID = pp.GetKey();
            log.Info("AD_Window_ID=" + AD_Window_ID + " - " + query);
            //GenerateWindow frame = new GenerateWindow();
            // get window
            //VAdvantage.Framework.VForm obj = frame.InitilizeWindow(query, false, AD_Window_ID);
            Apps.AWindow frame = new VAdvantage.Apps.AWindow();
            frame.Initialized += (s, e) =>
            {
                Dispose(true);
            };

            if (frame.InitWindow(AD_Window_ID, query))//   obj != null)
            {
                // show the window
               // frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
               // frame.Show();
            }
            //obj = null;
            frame = null;
        }

    }

}

